const gulp =require('gulp');
const concat = require('gulp-concat');
const del = require('del');
const htmlMin = require('gulp-htmlmin');

const sass = require('gulp-sass')(require('sass'));
const autoprefixer = require('gulp-autoprefixer');
const cleanCSS = require('gulp-clean-css');
const rename = require('gulp-rename');
const uglify = require('gulp-uglify');
const connect = require('gulp-connect');

// 清空build目录
function cleanAll() {
  return del(['build/**']);
}

// 压缩html
function html() {
  return gulp.src('src/*.html')
    .pipe(htmlMin({collapseWhitespace: true}))
    .pipe(gulp.dest('build/'))
    .pipe(connect.reload())
}

// 清空src下的css目录
function cleanCss() {
  return del(['src/css/**']);
}

// scss生成css, 放到src/css目录下
function scss() {
  return gulp.src('src/scss/*.scss')
    .pipe(autoprefixer())
    .pipe(sass())
    .pipe(gulp.dest('src/css'))
}

// 合并压缩css, 放到build/h-ui/css 目录下
function css() {
  return gulp.src('src/scss/*.scss')
    .pipe(autoprefixer())
    .pipe(concat('H-ui.css'))
    .pipe(sass())
    .pipe(gulp.dest('build/h-ui/css'))
    .pipe(cleanCSS({compatibility: 'ie8'}))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('build/h-ui/css'))
    .pipe(connect.reload())
}

// 合并压缩js, 放到build/h-ui/js 目录下
function js() {
  return gulp.src('src/js/*.js')
    .pipe(concat('H-ui.js'))
    .pipe(gulp.dest('build/h-ui/js'))
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('build/h-ui/js'))
    .pipe(connect.reload())
}

// image——放到build/h-ui/images 目录下
function image() {
  return gulp.src('src/images/**')
    .pipe(gulp.dest('build/h-ui/images'))
}

// 将lib放到build/lib 目录下
function lib() {
  return gulp.src('src/lib/**')
    .pipe(gulp.dest('build/lib'))
}

// 将ico文件放到build 目录下
function ico() {
  return gulp.src('src/*.ico')
    .pipe(gulp.dest('build/'))
}

// 启动一个9003端口的web服务
function server() {
  connect.server({
    root: 'build',
    livereload: true,
    port: 9003
  })
}

exports.cleanAll = cleanAll;
exports.html = html;
exports.scss = gulp.series(cleanCss, gulp.parallel(scss));
exports.css = css;
exports.js = js;
exports.image = image;
exports.lib = lib;
exports.ico = ico;
exports.server = server;

// 监视服务，监视文件变化，自动build
function watch() {
  gulp.watch('src/js/*.js', gulp.parallel(['js']));
  gulp.watch('src/scss/*.scss', gulp.parallel(['css']));
  gulp.watch('src/images/**', gulp.parallel(['image']));
  gulp.watch('src/*.html', gulp.parallel(['html']));
}
exports.watch = watch;

const build = gulp.series(cleanAll, gulp.parallel(html, css, js, image, lib, ico));
exports.build = build;

exports.start = gulp.series(build, gulp.parallel(server, watch))

